<script setup name="Item">

import {nextTick} from 'vue'
import getSearchConfig from './config/searchConfig'
import getContentConfig from './config/contentConfig.js'
import getDialogConfig from './config/dialogConfig.js'
import useDialog from '@/hooks/useDialog'
import getComputedConfig from '@/hooks/getPageConfig'
import {emailBaseUrl} from '@/api/config/base.js'
import {getMailImportHistory, sendEmailByImportHistoryIds} from "@/api/email/history.js";
import {sendEmailByMailItemId} from "@/api/email/item.js";
import to from "@/utils/to.js";

const props = defineProps({
  mailImportHistoryId: {
    type: String,
    required: false,
    default: '',
  },
  tableHideItems: {
    type: Array,
    default: () => [],
    required: false,
  },
  showSearch: {
    type: Boolean,
    required: false,
    default: true,
  },
  showSend: {
    type: Boolean,
    required: false,
    default: true,
  },
  showPagination: {
    type: Boolean,
    required: false,
    default: true,
  },
});
const emit = defineEmits(['update:mailImportHistoryId']);

const mailImportHistoryIdComputed = computed(() => {
  return props.mailImportHistoryId
})

const otherRequestOption = ref({
  mailImportHistoryId: mailImportHistoryIdComputed.value,
})


const {proxy} = getCurrentInstance();
const {sys_email_send_status} = proxy.useDict('sys_email_send_status')


const pageName = 'item'
const idKey = 'mailItemId'
const requestBaseUrl = emailBaseUrl
const pageSearchRef = ref(null)
const pageContentRef = ref(null)
const descConfig = ref({})
const dialogHideItems = ref([])


const dictMap = {
  status: sys_email_send_status,
}

// 列表头部按钮
const headerButtons = ['refresh', 'delete']
if (props.showSearch) {
  headerButtons.push('comSearch')
}

const searchConfig = getSearchConfig()
const searchConfigComputed = computed(() => {
  return getComputedConfig(searchConfig, dictMap)
})
const tableSelected = ref([])
const tableListener = {
  selectionChange: (selected) => {
    tableSelected.value = selected
  },
}
const tableHideItemsComputed = computed(() => {
  return props.tableHideItems
})

const contentConfig = getContentConfig()
const contentConfigComputed = computed(() => {
  contentConfig.hideItems = tableHideItemsComputed.value
  contentConfig.pagination = props.showPagination
  return contentConfig
})

const dialogConfig = getDialogConfig()

const dialogConfigComputed = computed(() => {
  dialogConfig.hideItems = dialogHideItems
  return getComputedConfig(dialogConfig, dictMap)
})

const addCallBack = () => {
  dialogHideItems.value.length = 0
}
const editCallBack = (item, type, res) => {
  isEditMore.value = type
}
const isEditMore = ref(false)
const editMoreClick = () => {
  if (tableSelected.value.length > 0) {
    const data = tableSelected.value[0]
    pageContentRef.value?.editClick(data, true)
    nextTick(() => {
      const newArray = tableSelected.value.slice(1)
      dialogRef.value?.changeSelected(newArray)
    })
  }
}

const editNext = (data) => {
  pageContentRef.value?.editClick(data, true)
}

const [dialogRef, infoInit, addClick, editBtnClick] = useDialog(
    addCallBack,
    editCallBack,
    '添加'
)

const dialogWidth = ref('1200px')
const searchData = computed(() => {
  return pageContentRef.value?.finalSearchData
})

const search = () => {
  pageSearchRef.value?.search()
}

const beforeSend = (queryInfo) => {
}

const permission = ref({})

const onChangeShowColumn = (filterArr) => {
  // tableHideItems.value = filterArr
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy.download(
      'email/item/export',
      {
        ...searchData.value,
      },
      `item_${new Date().getTime()}.xlsx`
  )
}

const mailImportHistory = ref({})
const handleGetMailImportHistory = () => {
  if (mailImportHistoryIdComputed.value !== '') {
    getMailImportHistory(mailImportHistoryIdComputed.value).then(({code, data}) => {
      if (code === 200) {
        mailImportHistory.value = data
      }
    }).catch((err) => {
      console.log(err)
    })
  }
}
handleGetMailImportHistory()

const handleSendEmail = async () => {
  if (tableSelected.value.length > 0) {
    const data = tableSelected.value
    const ids = data.map(item => item[idKey])
    proxy.$modal.confirm(`选中${tableSelected.value.length}条数据，是否确认发送邮件?`).then(async () => {
      console.log('确认', ids)
      const [err, res] = await to(sendEmailByMailItemId(ids))
      const {msg, code} = res
      if (code === 200) {
        console.log('发送成功')
      } else {
        proxy.$modal.notifyError(msg)
      }
    }).catch(() => {
    }).finally(() => {
    })
  } else {
    proxy.$modal.notifyWarning('请选择要发送邮件的明细记录')
  }
}
const init = () => {
}

init()
</script>
<template>
  <div class="default-main page">

    <el-descriptions v-if="mailImportHistoryIdComputed !== ''" class="descriptions" title="导入模板信息" size="large"
                     :column="4" border>
      <el-descriptions-item label="导入编号">{{ mailImportHistory.code }}</el-descriptions-item>
      <el-descriptions-item label="导入文件名称">{{ mailImportHistory.fileName }}</el-descriptions-item>
      <el-descriptions-item label="导入时间">{{ mailImportHistory.createTime }}</el-descriptions-item>
      <el-descriptions-item label="文件大小">{{ mailImportHistory.fileSize }}</el-descriptions-item>
    </el-descriptions>

    <PageSearch v-if="showSearch"
                ref="pageSearchRef"
                :pageName="pageName"
                :searchConfig="searchConfigComputed"
    ></PageSearch>
    <PageContent
        ref="pageContentRef"
        :pageName="pageName"
        :idKey="idKey"
        :contentConfig="contentConfigComputed"
        :descConfig="descConfig"
        :dictMap="dictMap"
        :tableListener="tableListener"
        :tableSelected="tableSelected"
        :permission="permission"
        :requestBaseUrl="requestBaseUrl"
        :otherRequestOption="otherRequestOption"
        :headerButtons="headerButtons"
        @beforeSend="beforeSend"
        @addClick="addClick"
        @editBtnClick="editBtnClick"
        @onChangeShowColumn="onChangeShowColumn"
        @editMoreClick="editMoreClick"
    >
      <template #handleLeft>
        <el-button
            v-if="showSend"
            class="order17 ml12"
            type="primary"
            @click="handleSendEmail"
        >
          <SvgIcon size="14" iconClass="guide"/>
          <span class="ml6">发信</span>
        </el-button>
      </template>
      <template #statusSlot="{ backData }">
        <el-tag :type="backData.status === '1' ? 'success' : 'warning'">
          {{ backData.status === '1' ? '成功' : backData.status === '0' ? '失败' : '待发送' }}
        </el-tag>
      </template>

    </PageContent>
    <PageDialog
        ref="dialogRef"
        :width="dialogWidth"
        :pageName="pageName"
        :idKey="idKey"
        :sendIdKey="idKey"
        :dialogConfig="dialogConfigComputed"
        :infoInit="infoInit"
        :search="search"
        :isEditMore="isEditMore"
        :requestBaseUrl="requestBaseUrl"
        @editNext="editNext"
    />

  </div>
</template>

<style scoped lang="scss">
.page {
  :deep(.statusClass .el-radio-group) {
    width: 100%;

    .el-radio {
      margin-right: 16px;
    }
  }

  :deep(.del) {
    margin-left: 12px;
  }

  .descriptions {
    border: 1px solid #e8eaec;
    margin: 0 0 10px 0;
    padding: 15px;
  }
}
</style>
